package com.it.smn.divide.postprocessor;

import com.it.smn.divide.exception.DivideException;
import com.it.smn.divide.registrar.DynamicDataSourceRegistrar;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.sql.DataSource;
import java.util.Map;
import java.util.Set;

/**
 * @author sunmannian
 * @ClassName com.it.smn.divide.postprocessor.DivideBeanFactoryPostProcessor
 * @Date 2020/8/27 17:28
 * @Version V1.0
 * Description  <请输入一句话描述该类功能>
 * Copyright (C) 北京中电兴发科技有限公司  since 2020/8/27
 */
@Component
public class DivideBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        Map<String, DataSource> beansOfType = beanFactory.getBeansOfType(DataSource.class);
        if (CollectionUtils.isEmpty(beansOfType)) {
            throw new DivideException("can not detect any DataSource");
        }
        BeanDefinition beanDefinition = beanFactory.getBeanDefinition(DynamicDataSourceRegistrar.BEAN_NAME);
        Set<String> names = beansOfType.keySet();
        String[] beanNames = new String[names.size()];
        names.toArray(beanNames);
        beanDefinition.setDependsOn(beanNames);
    }
}
